﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Kinect;

namespace SampleKinectProjectWPF
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        KinectSensor _nui;
        const int bytesPerVideoPixel = 4;
        byte[] _colorValues = new byte[640 * 480 * bytesPerVideoPixel];
        short[] _depthValues = new short[640 * 480];

        public MainWindow()
        {
            InitializeComponent();

            _nui = KinectSensor.KinectSensors[0];
            _nui.ColorStream.Enable(ColorImageFormat.RgbResolution640x480Fps30);
            _nui.DepthStream.Enable(DepthImageFormat.Resolution640x480Fps30);


            _nui.DepthFrameReady += new EventHandler<DepthImageFrameReadyEventArgs>(_nui_DepthFrameReady);
            _nui.ColorFrameReady += new EventHandler<ColorImageFrameReadyEventArgs>(_nui_ColorFrameReady);

            this.Closed += new EventHandler(MainWindow_Closed);

            _nui.Start();
        }

        void _nui_ColorFrameReady(object sender, ColorImageFrameReadyEventArgs e)
        {
            var thisFrame = e.OpenColorImageFrame();
            if (thisFrame != null)
            {
                thisFrame.CopyPixelDataTo(_colorValues);

                imageVideo.Source = BitmapSource.Create(
                    thisFrame.Width, thisFrame.Height, 96, 96, PixelFormats.Bgr32, null, _colorValues, thisFrame.Width * thisFrame.BytesPerPixel);

                thisFrame.Dispose();
            }
        }

        void _nui_DepthFrameReady(object sender, DepthImageFrameReadyEventArgs e)
        {
            var thisFrame = e.OpenDepthImageFrame();
            if (thisFrame != null)
            {
                thisFrame.CopyPixelDataTo(_depthValues);

                imageDepth.Source = BitmapSource.Create(
                    thisFrame.Width, thisFrame.Height, 96, 96, PixelFormats.Gray16, null, _depthValues, thisFrame.Width * thisFrame.BytesPerPixel);

                thisFrame.Dispose();
            }
        }

        void MainWindow_Closed(object sender, EventArgs e)
        {
            _nui.Stop();
        }
        
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
    }
}
